package cn.wostore.wxhelper.utils;

import android.util.Log;
import de.robv.android.xposed.XposedBridge;

import java.io.*;

/**
 * @author wuch
 * @date 2018/12/26 0026
 */
public class TxtUtil {
    /**
     * 读入TXT文件
     */
    public static String readFile(String path) {
        String line=null;
        try {
            File file = new File(path);
            int length = (int) file.length();
            byte[] buff = new byte[length];
            FileInputStream fis = new FileInputStream(file);
            fis.read(buff);
            fis.close();
            line = new String(buff, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return line;
    }

    /**
     * 写入TXT文件
     */
    public static void writeFile(String path, String fileName, String str) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(path, fileName);

        String strFilePath = path + fileName;
        // 每次写入时，都换行写
        //String strContent = str + "\r\n";
        try {
            File writeName = new File(strFilePath); // 相对路径，如果没有则要建立一个新的output.txt文件
            writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
            try (FileWriter writer = new FileWriter(writeName);
                 BufferedWriter out = new BufferedWriter(writer)
            ) {
                out.write(str);
                out.flush(); // 把缓存区内容压入文件
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 生成文件
    private static void makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 生成文件夹
    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }
}
